/**
 * Notes: 活动后台管理
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2022-06-23 07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const ActivityService = require('../activity_service.js');
const AdminHomeService = require('../admin/admin_home_service.js');
const util = require('../../../../framework/utils/util.js');
const cloudUtil = require('../../../../framework/cloud/cloud_util.js');
const cloudBase = require('../../../../framework/cloud/cloud_base.js');
const timeUtil = require('../../../../framework/utils/time_util.js');
const dataUtil = require('../../../../framework/utils/data_util.js');
const ActivityModel = require('../../model/activity_model.js');
const ActivityJoinModel = require('../../model/activity_join_model.js');
const exportUtil = require('../../../../framework/utils/export_util.js');
const md5Lib = require('../../../../framework/lib/md5_lib.js');

// 导出报名数据KEY
const EXPORT_ACTIVITY_JOIN_DATA_KEY = 'EXPORT_ACTIVITY_JOIN_DATA';

class AdminActivityService extends BaseProjectAdminService {
	/**取得分页列表 */
	async getAdminActivityList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal
	}) {
		orderBy = orderBy || {
			'ACTIVITY_ORDER': 'asc',
			'ACTIVITY_ADD_TIME': 'desc'
		};
		let fields = 'ACTIVITY_JOIN_CNT,ACTIVITY_TITLE,ACTIVITY_CATE_ID,ACTIVITY_CATE_NAME,ACTIVITY_MAX_CNT,ACTIVITY_START,ACTIVITY_END,ACTIVITY_STOP,ACTIVITY_ROOM_ID,ACTIVITY_ADDRESS,ACTIVITY_ADDRESS_GEO,ACTIVITY_CANCEL_SET,ACTIVITY_CHECK_SET,ACTIVITY_IS_MENU,ACTIVITY_ORDER,ACTIVITY_STATUS,ACTIVITY_VOUCH,ACTIVITY_FORMS,ACTIVITY_CAR_LIST,ACTIVITY_JOIN_FORMS,ACTIVITY_ADD_TIME,ACTIVITY_EDIT_TIME,ACTIVITY_QR,ACTIVITY_OBJ';
		let where = {};
		where.and = {
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};

		if (util.isDefined(search) && search) {
			where.or = [{
				ACTIVITY_TITLE: ['like', search]
			},];
		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.ACTIVITY_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.ACTIVITY_STATUS = Number(sortVal);
					break;
				}
				case 'vouch': {
					where.and.ACTIVITY_VOUCH = 1;
					break;
				}
				case 'top': {
					where.and.ACTIVITY_ORDER = 0;
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'ACTIVITY_ADD_TIME');
					break;
				}
			}
		}

		return await ActivityModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
	}

	/**置顶与排序设定 */
	async sortActivity(id, sort) {
		let where = {
			_id: id
		};
		let data = {};
		data.ACTIVITY_ORDER = sort;
		await ActivityModel.edit(where, data);
	}

	/**获取活动详情信息 */
	async getActivityDetail(id) {
		let fields = '*';
		let where = {
			_id: id
		}
		let activity = await ActivityModel.getOne(where, fields);
		if (!activity) return null;
		return activity;
	}


	/**首页设定 */
	async vouchActivity(id, vouch) {
		let where = {
			_id: id
		};
		let data = {};
		data.ACTIVITY_VOUCH = vouch;
		await ActivityModel.edit(where, data);
	}

	/**添加 */
	async insertActivity({
		title,
		cateId,
		cateName,
		maxCnt,
		start,
		end,
		stop,
		roomId,
		address,
		addressGeo,
		cancelSet,
		checkSet,
		isMenu,
		order,
		forms,
		carIds,
		joinForms,
	}) {
		let data = {};
		data.ACTIVITY_TITLE = title;
		data.ACTIVITY_CATE_ID = cateId;
		data.ACTIVITY_CATE_NAME = cateName;
		data.ACTIVITY_ROOM_ID = roomId;
		data.ACTIVITY_ADDRESS = address;
		data.ACTIVITY_ADDRESS_GEO = addressGeo;
		data.ACTIVITY_MAX_CNT = maxCnt;
		data.ACTIVITY_START = timeUtil.time2Timestamp(start);
		data.ACTIVITY_END = timeUtil.time2Timestamp(end);
		data.ACTIVITY_STOP = timeUtil.time2Timestamp(stop);
		data.ACTIVITY_CANCEL_SET = cancelSet;
		data.ACTIVITY_CHECK_SET = checkSet;
		data.ACTIVITY_IS_MENU = isMenu;
		data.ACTIVITY_ORDER = order;
		data.ACTIVITY_IS_MENU = isMenu;
		data.ACTIVITY_FORMS = forms;
		data.ACTIVITY_CAR_LIST = carIds,
		data.ACTIVITY_JOIN_FORMS = joinForms;
		return await ActivityModel.insert(data);
	}

	//#############################   
	/** 清空活动报名数据 */
	async clearActivityJoinData(activityId) {
		let where = {
			ACTIVITY_JOIN_ACTIVITY_ID: activityId
		}
		return await ActivityJoinModel.del(where);
	}

	/**删除活动 */
	async delActivity(id) {
		let where = {
			_id: id
		}
		return await ActivityModel.del(where);
	}
	
	// 更新forms信息
	async updateActivityForms({
		id,
		hasImageForms
	}) {
		return await ActivityModel.editForms(id, 'ACTIVITY_FORMS', 'ACTIVITY_OBJ', hasImageForms);
	}

	/**更新活动数据 */
	async editActivity({
		id,
		title,
		cateId, // 二级分类 
		cateName,
		maxCnt,
		start,
		end,
		stop,
		roomId,
		address,
		addressGeo,
		cancelSet,
		checkSet,
		isMenu,
		order,
		forms,
		carIds,
		joinForms
	}) {
		let data = {}
		data.ACTIVITY_TITLE = title;
		data.ACTIVITY_CATE_ID = cateId;
		data.ACTIVITY_CATE_NAME = cateName;
		data.ACTIVITY_ROOM_ID = roomId;
		data.ACTIVITY_ADDRESS = address;
		data.ACTIVITY_ADDRESS_GEO = addressGeo;
		data.ACTIVITY_MAX_CNT = maxCnt;
		data.ACTIVITY_START = timeUtil.time2Timestamp(start);
		data.ACTIVITY_END = timeUtil.time2Timestamp(end);
		data.ACTIVITY_STOP = timeUtil.time2Timestamp(stop);
		data.ACTIVITY_CANCEL_SET = cancelSet;
		data.ACTIVITY_CHECK_SET = checkSet;
		data.ACTIVITY_IS_MENU = isMenu;
		data.ACTIVITY_ORDER = order;
		data.ACTIVITY_IS_MENU = isMenu;
		data.ACTIVITY_FORMS = forms;
		data.ACTIVITY_CAR_LIST = carIds,
		data.ACTIVITY_JOIN_FORMS = joinForms;
		let where = {
			_id: id
		}
		return await ActivityModel.edit(where, data);
	}
	/**修改活动状态 */
	async statusActivity(id, status) {
		let where = {
			_id: id
		}
		let data = {
			ACTIVITY_STATUS: status
		}
		return await ActivityModel.edit(where, data);
	}
	//#############################
	/**报名分页列表 */
	async getActivityJoinList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		activityId,
		page,
		size,
		isTotal = true,
		oldTotal
	}) {
		orderBy = orderBy || {
			'ACTIVITY_JOIN_ADD_TIME': 'desc'
		};
		let fields = '*';

		let where = {
			ACTIVITY_JOIN_ACTIVITY_ID: activityId
		};
		if (util.isDefined(search) && search) {
			where['ACTIVITY_JOIN_FORMS.val'] = {
				$regex: '.*' + search,
				$options: 'i'
			};
		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'status':
					// 按类型  
					where.ACTIVITY_JOIN_STATUS = Number(sortVal);
					break;
				case 'checkin':
					// 签到
					where.ACTIVITY_JOIN_STATUS = ActivityJoinModel.STATUS.SUCC;
					if (sortVal == 1) {
						where.ACTIVITY_JOIN_IS_CHECKIN = 1;
					} else {
						where.ACTIVITY_JOIN_IS_CHECKIN = 0;
					}
					break;
			}
		}
		return await ActivityJoinModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
	}

	/**修改报名状态  
	 */
	async statusActivityJoin(activityJoinId, status, reason = '') {
		let where = {
			_id: activityJoinId
		}
		let data = {
			ACTIVITY_JOIN_STATUS: status
		}
		if (util.isDefined(reason)) {
			data.ACTIVITY_JOIN_REASON = reason
		}
		return await ActivityJoinModel.edit(where, data);
	}

	/** 安排车辆 */
	async arrangeActivityJoinCar(activityJoinId, carNum) {
		let where = {
			_id: activityJoinId
		}
		let data = {
			ACTIVITY_JOIN_CAR_TITLE: carNum
		}
		return await ActivityJoinModel.edit(where, data);
	}

	/** 取消某项目的所有报名记录 */
	async cancelActivityJoinAll(activityId, reason) {
		let where = {
			ACTIVITY_JOIN_ACTIVITY_ID: activityId
		}
		// TODO 待更新 activity 表 ACTICITY_USER_LIST, ACTICITY_JOIN_CNT
		return await ActivityJoinModel.del(where);
	}

	/** 删除报名 */
	async delActivityJoin(activityJoinId) {
		let where = {
			_id: activityJoinId
		}
		return await ActivityJoinModel.del(where);
	}

	/** 自助签到码 */
	async genActivitySelfCheckinQr(page, activityId) {
		let cloud = cloudBase.getCloud();

		if (page.startsWith('/')) page = page.substring(1);
		//console.log('page=' + page, ', scene=' + activityId);

		let result = await cloud.openapi.wxacode.getUnlimited({
			scene: activityId,
			width: 280,
			check_path: false,
			env_version: 'trial', //release,trial,develop
			page
		});
		let cloudPath = PID + '/' + 'selfcheckin/' + activityId + '.png';
		let upload = await cloud.uploadFile({
			cloudPath,
			fileContent: result.buffer,
		});
		if (!upload || !upload.fileID) return;

		let ret = await cloudUtil.getTempFileURLOne(upload.fileID);
		return ret + '?rd=' + this._timestamp;
	}

	/** 管理员按钮核销 */
	async checkinActivityJoin(activityJoinId, flag) {
		let where = {
			_id: activityJoinId
		}
		let data = {
			ACTIVITY_JOIN_IS_CHECKIN: flag,
			ACTIVITY_JOIN_CHECKIN_TIME: flag ? this._timestamp : 0
		}
		return await ActivityJoinModel.edit(where, data);
	}

	/** 管理员扫码核销 */
	async scanActivityJoin(activityId, code) {
		let where = {
			ACTIVITY_JOIN_ACTIVITY_ID: activityId,
			ACTIVITY_JOIN_CODE: code
		}
		let data = {
			ACTIVITY_JOIN_IS_CHECKIN: 1,
			ACTIVITY_JOIN_CHECKIN_TIME: this._timestamp
		}
		return await ActivityJoinModel.edit(where, data);
	}

	// #####################导出报名数据
	/**获取报名数据 */
	async getActivityJoinDataURL() {
		return await exportUtil.getExportDataURL(EXPORT_ACTIVITY_JOIN_DATA_KEY);
	}

	/**删除报名数据 */
	async deleteActivityJoinDataExcel() {
		return await exportUtil.deleteDataExcel(EXPORT_ACTIVITY_JOIN_DATA_KEY);
	}

	/**导出报名数据 */
	async exportActivityJoinDataExcel({
		activityId,
		status
	}) {
		let fields = '*';
		let where = {
			ACTIVITY_JOIN_ACTIVITY_ID: activityId
		};
		let orderBy = {
			'ACTIVITY_JOIN_ADD_TIME': 'desc'
		};
		if (Number(status) != 999) {
			where.ACTIVITY_JOIN_STATUS = Number(status);
		}

		let joinList = await ActivityJoinModel.getList(where, fields, orderBy);
		joinList = (joinList || {}).list
		let data = [['姓名','电话','会议室座位号','车牌号','车辆座位号','报名时间','报名状态','签到时间']]
		for (let i = 0;i < (joinList || []).length; i ++) {
			let name = ((joinList[i].ACTIVITY_JOIN_OBJ || '').name) || ''
			let phone = ((joinList[i].ACTIVITY_JOIN_OBJ || '').phone) || ''
			let carTitle = joinList[i].ACTIVITY_JOIN_CAR_TITLE || ''
			let carSeat = joinList[i].ACTIVITY_JOIN_CAR_SEAT || ''
			let roomSeat = joinList[i].ACTIVITY_JOIN_ROOM_SEAT || ''
			let joinTime = joinList[i].ACTIVITY_JOIN_ADD_TIME > 0 ? timeUtil.timestamp2Time(joinList[i].ACTIVITY_JOIN_ADD_TIME) : ''
			let checkinTime = joinList[i].ACTIVITY_JOIN_CHECKIN_TIME > 0 ? timeUtil.timestamp2Time(joinList[i].ACTIVITY_JOIN_CHECKIN_TIME) : ''
			let status = joinList[i].ACTIVITY_JOIN_STATUS
			if (status == 1) {
				status = '报名成功'
			} else if (status == 0) {
				status = '待审核'
			} else if(status == 99) {
				status = '审核未通过'
			} else {
				status = ''
			}
			data.push([name, phone, roomSeat, carTitle, carSeat, joinTime, status, checkinTime])
		}

		return await exportUtil.exportDataExcel(EXPORT_ACTIVITY_JOIN_DATA_KEY, '', joinList.length, data);
	}
}

module.exports = AdminActivityService;